package com.csyf.manager.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.csyf.manager.channel.base.PaymentVo;
import com.csyf.manager.entity.SysMerchant;
import com.csyf.manager.entity.SysPayment;
import com.csyf.manager.entity.SysTradeType;
import com.csyf.manager.service.PayMentBiz;
import com.csyf.manager.service.SysMerchBiz;
import com.csyf.manager.service.SysTradeTypeBiz;
import com.csyf.manager.service.impl.RedisService;
import com.csyf.manager.utils.*;
import com.csyf.manager.utils.page.JqGridVo;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: Enzo
 * @Date: 2018/4/1 17:31
 */
@Controller
@RequestMapping(value = "sys/payment")
public class PayMentController {


    @Autowired
    private SysTradeTypeBiz sysTradeTypeBiz;

    @Autowired
    private PayMentBiz payMentBiz;

    @Autowired
    private HttpSession httpSession;

    @Autowired
    private SysMerchBiz sysMerchBiz;

    @Autowired
    private RedisService redisService;


    @GetMapping("paymentview")
    public String pageview(Model model){

        SysMerchant userInfo = getUserInfo();

        List<SysTradeType> tradeTypeByMchId = sysTradeTypeBiz.findTradeTypeByMchId(userInfo.getMerchMerchantNo());
        List<SysTradeType> sysTradeTypes = new ArrayList<>();
        for (SysTradeType entry : tradeTypeByMchId) {
            if (entry.getTradeType().contains("DF")) {
                sysTradeTypes.add(entry);
            }
        }
        model.addAttribute("tradeList", sysTradeTypes);

        return "view/payment";
    }


    @ResponseBody
    @PostMapping(value = "orderDataList")
    public JqGridVo orderDataList(SysPayment vo, Integer rows, Integer page) {
        SysMerchant userInfo = getUserInfo();
        vo.setMchId(userInfo.getMerchMerchantNo());
        return payMentBiz.queryOrderByUserId(vo, page, rows);
    }



    @ResponseBody
    @RequestMapping(value = "exportExcle")
    public void exportExcle(SysPayment vo, HttpServletResponse response) throws Exception {
        SysMerchant userInfo = getUserInfo();
        vo.setMchId(userInfo.getMerchMerchantNo());
        JqGridVo jqGridVo = payMentBiz.queryOrderByUserId(vo, 1, 100000);
        List<?> rows1 = jqGridVo.getRows();

        ExportParams exportParams = new ExportParams("代付列表", "代付列表 ", ExcelType.XSSF);

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, SysPayment.class, rows1);

        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename="
                + URLEncoder.encode(getUserInfo().getMerchMerchantNo() + "_" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xlsx", "UTF-8"));

        sheets.write(outputStream);


        sheets.close();

    }

    /**
     * 跳转代付表单界面
     * @param model
     * @return
     */
    @GetMapping("paymentmanageview")
    public String paymentmanageview(Model model){

        SysMerchant userInfo = getUserInfo();

        List<SysTradeType> tradeTypeByMchId = sysTradeTypeBiz.findTradeTypeByMchId(userInfo.getMerchMerchantNo());
        List<SysTradeType> sysTradeTypes = new ArrayList<>();
        for (SysTradeType entry : tradeTypeByMchId) {
            if (entry.getTradeType().contains("DF")) {
                sysTradeTypes.add(entry);
            }
        }
        model.addAttribute("tradeList", sysTradeTypes);

        return "view/agentpaymentmanage";
    }


    /**
     * 代理商代付
     * @return
     */
    @ResponseBody
    @PostMapping(value = "agentDfManage")
    public ReturnData agentDfManage(PaymentVo vo) {
        ReturnData returnData = new ReturnData();
        SysMerchant userInfo = getUserInfo();

        if (null == userInfo) {
            returnData.setCode(10);
            returnData.setMsg("登录过期，请重新登录！");
            return returnData;
        }

        if (StringUtils.isBlank(vo.getVerifyCode())) {
            returnData.setCode(10);
            returnData.setMsg("短信验证码为空");
            return returnData;
        }

        //校验输入手机与代理商预留手机号是否一致
        SysMerchant agent = sysMerchBiz.queryAgentByMerchantNo(userInfo.getMerchMerchantNo());
        String reservedPhone = agent.getMerchPhone();

        try {
            //校验短信验证码
            String verCode = redisService.getPaymentSmsVerifyCode(reservedPhone);
            if (!vo.getVerifyCode().equals(verCode)) {
                returnData.setCode(10);
                returnData.setMsg("短信验证码错误，请重新输入");
                return returnData;
            }

            String yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

            Map<String, String> objectObjectHashMap = new TreeMap<>();
            objectObjectHashMap.put("mch_id", userInfo.getMerchMerchantNo());
            objectObjectHashMap.put("out_trade_no", IdGenerator.INSTANCE.nextId());
            objectObjectHashMap.put("account_name", vo.getAccount_name());
            objectObjectHashMap.put("bank_card", vo.getBank_card());
            objectObjectHashMap.put("bank_linked", vo.getBank_linked());
            objectObjectHashMap.put("trans_money", NumberHelpler.money2cent(vo.getTrans_money()).toString());
            objectObjectHashMap.put("bank_name", vo.getBank_name());
            objectObjectHashMap.put("bankBranchname", vo.getBankBranchname());
            objectObjectHashMap.put("bankProvince", vo.getBankProvince());
            objectObjectHashMap.put("bankCity", vo.getBankCity());
            objectObjectHashMap.put("bankCode", vo.getBankCode());
            objectObjectHashMap.put("service", vo.getService());
            //非必传
            if (StringUtils.isNotBlank(vo.getIdcard())) {
                objectObjectHashMap.put("idcard", vo.getIdcard());
            }
            if (StringUtils.isNotBlank(vo.getPhoneNo())) {
                objectObjectHashMap.put("phoneNo", vo.getPhoneNo());
            }

            String sign = SignUtils.map2signkey(objectObjectHashMap, userInfo.getMerchSignkey());
            objectObjectHashMap.put("sign", sign);


            String s = HttpHelper.doPostForm("http://103.243.182.195/cspay/api/v1/dftransRequest", objectObjectHashMap);
            Map<String,String> map = new Gson().fromJson(s, Map.class);

            String ret_code = map.get("ret_code");
            if ("SUCCESS".equalsIgnoreCase(ret_code)) {
                //校验通过之后清除redis缓存
                redisService.deletePaymentSmsVerifyCode(reservedPhone);

                returnData.setCode(0);
                returnData.setMsg("请求成功");
            } else {
                String ret_message = map.get("ret_message");
                returnData.setCode(10);
                returnData.setMsg(ret_message);
            }
            returnData.setCode(0);
            returnData.setMsg("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode(10);
            returnData.setMsg("请求失败");
            return returnData;
        }
        return returnData;
    }


    private SysMerchant getUserInfo() {
        return (SysMerchant) httpSession.getAttribute("login");
    }
}
